package com.itheima.reggie.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.LoginCode;
import com.itheima.reggie.common.PageParams;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    /**
     * 获取验证码，并发送验证码
     * @param phone
     * @param session
     * @return
     */
    @GetMapping("/code")
    public R getCode(String phone, HttpSession session){
        // log.info("phone...."+phone);
        String code = ValidateCodeUtils.generateValidateCode4String(6);
       //真实发送验证码的过程
      //  SMSUtils.sendMessage("签名","模板",phone,code);
        session.setAttribute(phone,code);
        return R.success(code);
    }

    /**
     * fornt的user登录
     * @param loginCode
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody LoginCode loginCode,HttpSession session){
        String newCode = (String) session.getAttribute(loginCode.getPhone());
        if (newCode==null){
            throw new CustomException("请输入手机号和验证码登录");
        }
        if(newCode.equalsIgnoreCase(loginCode.getCode())){
            User user = userService.findUserByPhone(loginCode.getPhone());
            if (user==null){
                user=new User();
                user.setPhone(loginCode.getPhone());
                userService.insert(user);
            }
            session.setAttribute("user",user);
            return R.success("登录成功");
        }else{
            return R.error("登录失败");
        }
    }

    /**
     * 退出登录
     * @param phone
     * @param session
     * @return
     */
    @PostMapping("/logout")
    public R logout(@RequestBody String phone ,HttpSession session){
        try {
            System.out.println(phone);
            session.removeAttribute(phone);
            return R.success("退出登录成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("退出登录失败!");
        }
    }
    @PostMapping("/loginout")
    public R logout(HttpSession session) {
        //让session失效，，同时释放空间
        session.invalidate();
        return R.success("退出成功");
    }
}
